# -*- coding:utf-8 -*-
# @FileName  :translate.py
# @Time      :2024/7/4 11:45
# @Author    :lin
import json, time, requests, ast
from datetime import datetime

API_KEY = "ioZb4KVL5KkChXOrH7nXV5A5"
SECRET_KEY = "kPHgfUMH2kbLgDMsU1YYN06xb9KLER0D"


def get_access_token():
    """
    使用 AK，SK 生成鉴权签名（Access Token）
    :return: access_token，或是None(如果错误)
    """
    url = "https://aip.baidubce.com/oauth/2.0/token"
    params = {"grant_type": "client_credentials", "client_id": API_KEY, "client_secret": SECRET_KEY}
    return str(requests.post(url, params=params).json().get("access_token"))


def get_token(filepath='token.txt'):
    """读取外部文件，判断天数是否需要重新获取token"""
    with open(filepath, "r+") as f:
        first_line = f.readline().strip()
        second_line = f.readline().strip()
        doing_date = datetime.strptime(first_line, "%Y-%m-%d")
        now_date = datetime.now()
        if (now_date - doing_date).days > 10:
            f.seek(0)
            f.write(now_date.strftime("%Y-%m-%d") + "\n" + str(get_access_token()) + "\n")
            print("token已过期，已重新获取token", datetime.now().replace(microsecond=0))
            return get_access_token()
        else:
            print("token未过期，无需重新获取token", datetime.now().replace(microsecond=0))
            return second_line


# token = get_token()


def baidu_trans(_from, _to, _q, token):
    # url = "https://aip.baidubce.com/rpc/2.0/mt/texttrans/v1?access_token=" + get_access_token()
    url = "https://aip.baidubce.com/rpc/2.0/mt/texttrans/v1?access_token=" + token
    payload = json.dumps({
        "from": _from,
        "to": _to,
        "q": _q
    })
    headers = {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
    }
    response = requests.request("POST", url, headers=headers, data=payload)

    # print(response.text)
    return response.json()


def deepseek_v3_translate(text, language):
    text_list = [x.replace("\r", "").replace("\t", "").strip() for x in text.split("\n")]
    text_list = [x for x in text_list if x]  # 删除空字符串
    text_str = "\n".join(text_list)
    url = "https://api.siliconflow.cn/v1/chat/completions"
    # language = "原文，法语，德语，日语，韩语，葡萄牙语，西班牙语，越南语，印尼语，意大利语，泰语，土耳其语，俄罗斯语，中文繁体"
    payload = json.dumps({
        "model": "deepseek-ai/DeepSeek-V3",
        "messages": [
            {
                "role": "system",
                "content": f"""你是一个语言翻译专家，将用户输入翻译成{language}。用户可以向助手发送需要翻译的内容，助手会回答相应的翻译结果，返回一个二维列表。例如：输入 '你好\n世界' 返回：[['你好'，'Bonjour',...], ['世界'，'monde'], ...]，不需要返回代码块，api接口调用，并确保符合目标语言习惯，你可以调整语气和风格，并考虑到某些词语的文化内涵和地区差异。同时作为翻译家，需将原文翻译成具有信达雅标准的译文。\"信\" 即忠实于原文的内容与意图；\"达\" 意味着译文应通顺易懂，表达清晰；\"雅\" 则追求译文的文化审美和语言的优美。目标是创作出既忠于原作精神，又符合目标语言文化和读者审美的翻译。"""
            },
            {
                "role": "user",
                "content": text_str,
                # "content": f"""你是一个翻译专家，将用户输入翻译成{language}，返回一个二维列表。例如：输入 '你好\n世界' 返回：[['你好'，'Bonjour',...], ['世界'，'monde'], ...]，不需要返回代码块，api接口调用
                # 现在处理以下文本： {text_str}''"""
            }
        ]
    })
    headers = {
        'Authorization': 'Bearer sk-nwiheobxrjpjacwnyasvycpioddqythxaswdkxemflsxtpur',
        'Content-Type': 'application/json'
    }

    response = requests.request("POST", url, headers=headers, data=payload)
    res = response.json()
    print(res)
    choices = res.get("choices")
    if not choices:
        return {"info": "deepseek-v3翻译接口返回错误"}
    result = choices[0]['message']['content']
    if not result:
        return {"info": "deepseek-v3翻译接口返回错误"}
    try:
        data_list = ast.literal_eval(result)
    except:
        data_list = json.loads(result)
    if len(data_list) == 1 and len(text_list) != 1:
        data_list = data_list[0]
    content = '\n'.join(['\t'.join(x) for x in data_list])
    return {"data": data_list, "language": language, "content": content}


def translate(text, language, token):
    text_list = [x.replace("\r", "").replace("\t", "").strip() for x in text.split("\n")]
    text_list = [x for x in text_list if x]  # 删除空字符串
    data = {item: [item] for item in text_list}
    info = []
    for _to in language[1:]:
        _text = "\n".join(text_list)
        time.sleep(0.2)
        _trans = baidu_trans("auto", _to, _text, token)
        error_msg = _trans.get("error_msg")
        if error_msg:
            print(f"翻译{_to}时出现错误：{error_msg}")
            info.append(f"翻译{_to}时出现错误：{error_msg}")
            continue
        for item in _trans["result"]["trans_result"]:
            src = item["src"]  # 原文
            dst = item["dst"]  # 译文
            if src in data.keys():
                data[src].append(dst)
        print("to", _to, "translate success!")
    # 转置矩阵
    data_list = [data.get(key) for key in data.keys()]
    content = '\n'.join(['\t'.join(x) for x in data_list])
    info_str = "\n".join(info)
    return {"data": data_list, "info": info_str, "language": language, "content": content}
